package com.yurun.accountservice.tcc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yurun.accountservice.mapper.AccountMapper;
import com.yurun.domain.Account;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @author Xi Gao
 * @date 2020/9/13 11:28
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class AccountActionServiceImpl implements AccountActionService {

    @Resource
    private AccountMapper accountMapper;


    /**
     * @param context
     * @param userId
     * @param money
     * @return
     */
    @Override
    public boolean reducerAccountMoney(BusinessActionContext context, String userId, Integer money) {
        //先查询一下
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Account account = accountMapper.selectOne(queryWrapper);
        if (account == null) {
            log.info("无此用户信息");
            return false;
        }
        if (account.getMoney() < money) {
            log.info("余额不足");
            return false;
        }

        //减少用户的账户的余额
        int i = accountMapper.updateAccountMoney(userId, money);
        if (i > 0) {
            //记录成功阶段执行
            ResultHolder.setResult(getClass(), context.getXid(), "T");
            return true;
        } else {
            log.info("更新失败");
            return false;
        }

    }


    /**
     * 提交阶段，如果有需要做的动作就进行操作
     *
     * @param context
     * @return
     */
    @Override
    public boolean mycommit(BusinessActionContext context) {
        log.info("二阶段提交===开始");
        if (ResultHolder.getResult(getClass(), context.getXid()) == null) {
            return true;
        }
        //若提交还有动作就提交做
        ResultHolder.removeResult(getClass(), context.getXid());
        log.info("二阶段提交===结束");
        return true;
    }


    /**
     * 将 money 加回来
     *
     * @param context
     * @return
     */
    @Override
    public boolean myrollBack(BusinessActionContext context) {
        log.info("二阶段回滚===开始");
        //防止重复回滚
        if (ResultHolder.getResult(getClass(), context.getXid()) == null) {
            return true;
        }
        String userId = (String) context.getActionContext("userId");
        Integer money = (Integer) context.getActionContext("money");
        log.info("用户编号：{}，金额：{}", userId, money);
        //金额回滚回去
        int i = accountMapper.updateAccountMoney(userId, -money);
        //如果rollBack失败怎么办 ？？
        ResultHolder.removeResult(getClass(), context.getXid());
        log.info("二阶段回滚===结束");
        return true;
    }


}
